package xiaoa.java.net;

import java.io.BufferedReader;
import java.io.File;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;

import org.apache.commons.io.FileUtils;

/**
 * 客户端处理类
 * @author xiaoa
 * @date 2017年8月10日 下午11:43:22
 * @version V1.0
 *
 */
public class ClientHandler {

	/**
	 * 处理
	 */
	
	public static void doHandler(Socket socket)throws Throwable{
		
	    InetAddress local =  socket.getLocalAddress();
		
		System.out.println("====local host = " + local.getHostAddress() + "  port = " + socket.getPort());

		System.out.println("====client host = " + socket.getInetAddress().getHostAddress() + "  port = " + socket.getPort());

		try (OutputStream  out =  socket.getOutputStream()){
			
			String  resp = "GET / HTTPS/1.1\n"
                    +"Accept:text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8\n"
                    +"Accept-Encoding:utf-8, deflate, sdch\n"
                    +"Accept-Language:zh-CN,zh;q=0.8\n"
                    +"Cache-Control:max-age=0\n"
                    +"Connection:keep-alive\n"
                    +"Host:www.dagolfla.com\n"
                    +"Upgrade-Insecure-Requests:1\n"
                    +"User-Agent:Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36\n"
	                 +"\n";
				
			out.write(resp.getBytes() );
			out.flush();
			
			System.out.println("发送结束");
			
			// 获取输入流
			InputStream  input =  socket.getInputStream();
		
			BufferedReader  reader = new BufferedReader(new InputStreamReader(input));
			
			String line = null;
			
			// 长度
			StringBuilder respSb = new StringBuilder();
			
			while((line = reader.readLine()) != null ){
				
				respSb.append(line +"\n");
				System.out.println(line);
				
			}
			
		   FileUtils.writeStringToFile(new File("e://http.txt"), respSb.toString(), "utf-8");
			
		   System.out.println("应用结束");
						
		} catch (Exception e) {
			throw e;
		}
		
		
		
	}
	
	

}
